package com.dllo.lanou.cookapp.fragment;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.dllo.lanou.cookapp.R;
import com.dllo.lanou.cookapp.activity.AddCookContentActivity;
import com.dllo.lanou.cookapp.adapter.AddCookStrpAdapter;
import com.dllo.lanou.cookapp.entity.AddCookEntity;
import com.dllo.lanou.cookapp.entity.AddCookStepEntity;
import com.dllo.lanou.cookapp.entity.AddCookStepToYun;
import com.dllo.lanou.cookapp.entity.StepListToYun;
import com.dllo.lanou.cookapp.entity.User;
import com.dllo.lanou.cookapp.utils.ScrollViewUtil;
import com.dllo.lanou.cookapp.view.MyListView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * Created by xijinhua on 2016/3/21.
 */
public class AddShowCookFragment extends Fragment implements View.OnClickListener, AddCookStrpAdapter.ValueListener {
@Bind(R.id.button)
    Button button;
    @Bind(R.id.add_listview)
    MyListView listView;
    @Bind(R.id.add_show)
    ImageView show_img;
    @Bind(R.id.add_name)
    TextView add_name;
    @Bind(R.id.add_food)
    TextView add_food;
    @Bind(R.id.add_des)
    TextView add_des;
    @Bind(R.id.send_cook)
    TextView send_cook;
    @Bind(R.id.add_card)
    TextView  add_card;
    @Bind(R.id.add_label)
    TextView add_label;
    private List<AddCookEntity> addCookEntities = new ArrayList<>();
    private AddCookEntity addCookEntity = null;
    private int count =1;
    private AddCookStrpAdapter adapter;
    private String cookName,cookDes,cookFood,cookCard,cookLabel;
    private String show_imgString;
    private String step_imgString;
    private AddCookStepEntity addCookStepEntity;




    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_addshowcook,null);

        ButterKnife.bind(this,view);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        adapter = new AddCookStrpAdapter(getActivity());
        adapter.setValueListener(this);
        if (count == 1){
           // stepListToYun = new StepListToYun();
            addCookEntity = new AddCookEntity();

           // stepListToYun.setCount(count + "");
           // stepListToYuns.add(stepListToYun);

            addCookEntity.setCount(count + "");
            addCookEntities.add(addCookEntity);
            adapter.addData(addCookEntity);
        }
        listView.setAdapter(adapter);
        ScrollViewUtil.setListViewHeightBasedOnChildren(listView);
        button.setOnClickListener(this);
        show_img.setOnClickListener(this);
        add_name.setOnClickListener(this);
        add_des.setOnClickListener(this);
        add_food.setOnClickListener(this);
        add_card.setOnClickListener(this);
        add_label.setOnClickListener(this);
        send_cook.setOnClickListener(this);


    }


    private void doYun() {


        final BmobFile bmobFile = new BmobFile(new File(show_imgString));
        bmobFile.uploadblock(getActivity(), new UploadFileListener() {

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
                //bmobFile.getUrl()---返回的上传文件的地址（不带域名）
                //bmobFile.getFileUrl(context)--返回的上传文件的完整地址（带域名）

                User user = BmobUser.getCurrentUser(getActivity(), User.class);
                addCookStepEntity = new AddCookStepEntity();
                addCookStepEntity.setAuthor(user);
                addCookStepEntity.setName(cookName + "");
                addCookStepEntity.setDes(cookDes + "");
                addCookStepEntity.setFood(cookFood + "");
                addCookStepEntity.setLabel(cookLabel + "");
                addCookStepEntity.setTips(cookCard + "");
                addCookStepEntity.setBmob_img(bmobFile.getFileUrl(getActivity()));
                addCookStepEntity.addAll("addCookEntities", addCookEntities);
                addCookStepEntity.save(getActivity(), new SaveListener() {
                    @Override
                    public void onSuccess() {
//                        Log.i("zhongyaoa","成功"+bmobFile.getUrl()+"LLL"+bmobFile.getFileUrl(get));
                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });

            }

            @Override
            public void onProgress(Integer value) {
                // TODO Auto-generated method stub
                // 返回的上传进度（百分比）
            }

            @Override
            public void onFailure(int code, String msg) {
                // TODO Auto-generated method stub
//                toast("上传文件失败：" + msg);
            }
        });



    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button:
                count++;
                Log.i("count",count+"");
               // stepListToYun = new StepListToYun();
                addCookEntity = new AddCookEntity();
                addCookEntity.setCount(count + "");
                addCookEntities.add(addCookEntity);
                adapter.addData(addCookEntity);
                break;
            case R.id.add_show:
                Intent intent_icon = new Intent();
                intent_icon.setAction(Intent.ACTION_GET_CONTENT);
                intent_icon.setType("image/*");
                startActivityForResult(intent_icon, 97);
                break;

            case R.id.add_name:
                Intent intent2 = toActivty();
                intent2.putExtra("title_content","添加菜谱名称");
                startActivityForResult(intent2, 96);
                break;

            case  R.id.add_des:
                Intent intent3 = toActivty();
                intent3.putExtra("title_content","添加简介");
                startActivityForResult(intent3, 95);
                break;

            case R.id.add_food:
                Intent intent4 = toActivty();
                intent4.putExtra("title_content","添加材料");
                startActivityForResult(intent4, 94);
                break;
            case R.id.add_card:
                Intent intent5 = toActivty();
                intent5.putExtra("title_content","添加小贴士");
                startActivityForResult(intent5, 93);
                break;

            case R.id.add_label:
                Intent intent6 = toActivty();
                intent6.putExtra("title_content","添加标签");
                startActivityForResult(intent6, 92);
                break;

            case R.id.send_cook:
                 //云端处理
                Log.i("zhongyaoa",addCookEntities.size()+"");


                doYun();
                break;
        }
    }

    @Override
    public void onClick(int postion) {
        addCookEntity = (AddCookEntity) adapter.getItem(postion);
        Intent intent_icon = new Intent();
                intent_icon.setAction(Intent.ACTION_GET_CONTENT);
                intent_icon.setType("image/*");
                //count++;
               startActivityForResult(intent_icon, 99);

    }

    @Override
    public void onContentClick(int postion) {
        addCookEntity = (AddCookEntity) adapter.getItem(postion);
        Intent intent = new Intent();
        intent.setClass(getActivity(), AddCookContentActivity.class);
        intent.putExtra("title_content", "添加内容");
        startActivityForResult(intent, 98);

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 99:
                if (data != null){
                    Uri imageUri = data.getData();
                    ContentResolver cr = getActivity().getContentResolver();
                    String[] proj ={MediaStore.Images.Media.DATA};
                    @SuppressWarnings("deprecation")
                    Cursor cursor =cr.query(imageUri, proj, null, null, null);
                    int photocolumn =  cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path = cursor.getString(photocolumn);
                    addCookEntity.setImg(path);
                    Log.i("本地图片", addCookEntity.getImg());
                    adapter.notifyDataSetChanged();
                    final BmobFile bmobFile = new BmobFile(new File(path));
                    bmobFile.uploadblock(getActivity(), new UploadFileListener() {

                        @Override
                        public void onSuccess() {
                            // TODO Auto-generated method stub
                            addCookEntity.setToYunImg(bmobFile.getFileUrl(getActivity()));
                            Log.i("本地图片+",bmobFile.getFileUrl(getActivity()));
                            //addCookEntities.add(addCookEntity);
                        }

                        @Override
                        public void onProgress(Integer value) {
                            // TODO Auto-generated method stub
                            // 返回的上传进度（百分比）
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            // TODO Auto-generated method stub

                        }
                    });
//                    adapter.addData(addCookEntity);
                    cursor.close();



                }

                break;

            case 98:
                if (data != null){
                    addCookEntity.setContent(data.getStringExtra("content"));
                    Log.i("img++++", addCookEntity.getCount() + addCookEntity.getImg());
//                    stepListToYun.setContent(data.getStringExtra("content"));
                   // addCookEntities.add(addCookEntity);
                    adapter.notifyDataSetChanged();
                }

                break;

            case 97:
                if (data != null){
                    Uri imageUri = data.getData();
                    ContentResolver cr = getActivity().getContentResolver();
                    Bitmap bm = null;
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(imageUri));
                        bm = compressBmpFromBmp(bitmap);
                        show_img.setImageBitmap(bm);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    String[] proj ={MediaStore.Images.Media.DATA};
                    @SuppressWarnings("deprecation")
                    Cursor cursor =cr.query(imageUri, proj, null, null, null);
                    int photocolumn =  cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    show_imgString = cursor.getString(photocolumn);

                    //imgs.add(path);
                    //   Log.i("我的图片",imgs+"");
//                    addCookEntity.setImg(path);
//                    Log.i("img++++", addCookEntity.getCount() + addCookEntity.getImg());
//                    adapter.notifyDataSetChanged();
//                    adapter.addData(addCookEntity);




                    cursor.close();



                }
                break;
            case 96:
                if (data != null){
                    cookName = data.getStringExtra("content");
                    add_name.setText(cookName);

                }
                break;
            case 95:
                if (data != null){
                    cookDes = data.getStringExtra("content");
                    add_des.setText(cookDes);
                }
                break;
            case 94:
                if (data != null){
                    cookFood = data.getStringExtra("content");
                    add_food.setText(cookFood);
                }
                break;
            case 93:
                if (data != null){
                    cookCard = data.getStringExtra("content");
                    add_card.setText(cookCard);
                }
                break;
            case 92:
                if (data != null){
                    cookLabel = data.getStringExtra("content");
                    add_label.setText(cookLabel);
                }
                break;
        }

    }

    private Bitmap compressBmpFromBmp(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 100;
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        while (baos.toByteArray().length / 1024 > 100) {
            baos.reset();
            options -= 10;
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    private Intent toActivty(){
        Intent  intent = new Intent();
        intent.setClass(getActivity(),AddCookContentActivity.class);
        return  intent;
    }
}
